package com.taplinker.client.im.rpc;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;

import android.content.Context;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;

import com.google.protobuf.ByteString;
import com.taplinker.client.AppConfigContext;
import com.taplinker.client.im.protocol.UploadRequest.UploadReq;
import com.taplinker.core.AppContextMessage;
import com.taplinker.core.AppSignal;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.rpc.command.SimpleBaseCommand;
import com.taplinker.core.rpc.http.HttpTemplate;
import com.taplinker.core.rpc.http.client.cache.CacheKey;
import com.taplinker.core.rpc.http.client.cache.HttpCacheDAO;
import com.taplinker.core.util.LogUtil;

public class UploadCommand extends SimpleBaseCommand {
	private File file;
	private Callback callback;

	public UploadCommand(File file, Context context, Callback callback) {
		super(context);
		this.file = file;
		this.callback = callback;
	}

	public UploadCommand(String path, Context context) {
		this(new File(path), context, null);
	}

	@Override
	public Result go() {

		UploadReq.Builder builder = UploadReq.newBuilder();
		try {
			byte[] bytes = new byte[(int) file.length()];
			FileInputStream stream = new FileInputStream(file);
			stream.read(bytes);
			builder.setFileType("amr");
			builder.setFile(ByteString.copyFrom(bytes));
			stream.close();
			return new HttpTemplate().postForGogoByte(
					AppConfigContext.TAPLINKER_WEB + "/services/upload",
					builder.build().toByteArray());
		} catch (Exception e) {
			LogUtil.d("http", "上传失败");
		}
		Result result = new Result();
		result.status = AppSignal.SERVER_ERROR;
		result.message = AppContextMessage.getMessage(result.status);
		return result;
	}

	@Override
	public void yes(Result result) {
		try {
			if (callback != null) {
				Message msg = new Message();
				msg.obj = result.object;
				callback.handleMessage(msg);
			}
			URL url = new URL(AppConfigContext.WEB_DISK_ROOT
					+ result.object.toString());
			HttpCacheDAO.getInstance().insert(
					CacheKey.getCacheKey(url.getPath()), file.getPath(), 1,
					"false");
			Log.d("tag", result.message);
		} catch (Exception e) {
			LogUtil.d("http", e.getMessage());
		}
	}
}
